<template>
    <base-breadcrumb :title="titleName">
        <a-row :gutter="20" class="page-height">
            <a-col span="6">
                <a-card v-loading="getTreeLoading" class="page-height-tree">
                    <!-- <title-name title="新技术类型" /> -->
                    <a-input-search style="margin-bottom: 8px" @change="onChange" />
                    <div :style="'height: calc('+GET_REDRESS_PERCENTAGE+'vh - 300px); overflow: auto'">
                        <a-tree
                            :expanded-keys="expandedKeys"
                            :auto-expand-parent="autoExpandParent"
                            :tree-data="treeData"
                            :selected-keys="selectedKeys"
                            @select="onSelect"
                            @expand="onExpand"
                        >
                            <template slot="title" slot-scope="{ title }">
                                <span v-if="title.indexOf(searchValue) > -1">
                                    {{ title.substr(0, title.indexOf(searchValue)) }}
                                    <span style="color: #f50">{{ searchValue }}</span>
                                    {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                                </span>
                                <span v-else>{{ title }}</span>
                            </template>
                        </a-tree>
                    </div>
                    <div class="options" style="margin-top: 20px; display: flex; justify-content: space-between">
                        <a-button v-btnPermission="'stm_007_addtype_06'" type="primary" @click="addTree(1)">
                            新增
                        </a-button>
                        <a-button
                            v-btnPermission="'stm_007_editype_07'"
                            :disabled="!editAble"
                            type="primary"
                            @click="addTree(2)"
                        >
                            编辑
                        </a-button>
                        <a-button
                            v-btnPermission="'stm_007_deltype_08'"
                            :loading="confirmLoading"
                            :disabled="!editAble"
                            type="info"
                            @click="delTree"
                        >
                            删除
                        </a-button>
                    </div>
                </a-card>
            </a-col>
            <a-col span="18" class="page-height-list-wrapper">
                <searchData ref="searchData" :search-data="searchArr" @search="search" />
                <a-card :bordered="false" class="page-height-list">
                    <!-- <title-name title="新技术列表" /> -->
                    <a-button
                        v-btnPermission="'stm_007_add_01'"
                        :disabled="canAdd"
                        class="mb12"
                        type="primary"
                        @click="handleAdd"
                    >
                        新增
                    </a-button>
                    <a-button
                        v-btnPermission="'stm_007_exp_09'"
                        :disabled="!selectTree"
                        class="ml12"
                        :loading="loadingExcel"
                        type="primary"
                        @click="downExcel"
                        icon="download"
                        >导出</a-button
                    >
                    <list-table
                        ref="table"
                        size="default"
                        row-key="technicalId"
                        :columns="columns"
                        :request="loadData"
                        show-pagination="auto"
                    >
                        <span slot="status" slot-scope="text">
                            <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
                        </span>
                        <template slot="action" slot-scope="text, record">
                            <MoreButton>
                                <!-- <a @click="handleSub(record)">查看</a> -->
                                <!-- <a-divider type="vertical" /> -->
                                <template v-if="record.status">
                                    <a
                                        v-btnPermission="'stm_007_edifo_05'"
                                        type="primary"
                                        @click="handleEdit(record)"
                                        >修改</a
                                    >
                                    <a
                                        v-btnPermission="'stm_007_clofo_06'"
                                        style="color: red"
                                        @click="handleSwitch(record, 0)"
                                        >停用</a
                                    >
                                </template>
                                <a v-else v-btnPermission="'stm_007_opefo_07'" @click="handleSwitch(record, 1)"
                                    >启用</a
                                >
                                <a v-btnPermission="'stm_007_del_05'" style="color: red" @click="handleDel(record)"
                                    >删除</a
                                >
                            </MoreButton>
                        </template>
                    </list-table>
                </a-card>
            </a-col>
        </a-row>
        <!-- <add-post
            ref="createModal"
            :visible="visible"
            :loading="confirmLoading"
            :model="mdl"
            :posttype='posttype'
            @cancel="handleCancel"
            @ok="handleOk"
            :title="title"
          /> -->
        <a-modal
            :title="title"
            :visible="visible"
            :confirm-loading="confirmLoading"
            width="1000px"
            ok-text="提交"
            @ok="handleOk"
            @cancel="handleCancel"
        >
            <a-form>
                <a-row :gutter="24">
                    <a-form-model
                        ref="form"
                        :model="form"
                        :rules="rules"
                        :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                        :wrapper-col="{ lg: { span: 15 }, sm: { span: 15 } }"
                    >
                        <a-col :span="24">
                            <a-row :gutter="24">
                                <a-col :md="24" :sm="24">
                                    <a-form-model-item
                                        prop="technicalName"
                                        label="新技术名称："
                                        :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                                        :wrapper-col="{ lg: { span: 15 }, sm: { span: 15 } }"
                                    >
                                        <BaseInput
                                            v-model.trim="form.technicalName"
                                            placeholder="请输入新技术名称"
                                            :max-length="50"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :md="12" :sm="12">
                                    <a-form-model-item
                                        label="实物量单位"
                                        :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                                        :wrapper-col="{ lg: { span: 15 }, sm: { span: 15 } }"
                                        prop="entityMeasureUnit"
                                    >
                                        <BaseInput
                                            v-model.trim="form.entityMeasureUnit"
                                            placeholder="请输入实物量单位"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :md="12" :sm="12">
                                    <a-form-model-item
                                        label="序号"
                                        :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                                        :wrapper-col="{ lg: { span: 15 }, sm: { span: 15 } }"
                                        prop="number"
                                    >
                                        <BaseInput v-model.trim="form.number" placeholder="请输入序号"  />
                                    </a-form-model-item>
                                </a-col>
                                <a-col :md="24" :sm="24">
                                    <a-form-model-item
                                        label="新技术描述"
                                        :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
                                        :wrapper-col="{ lg: { span: 15 }, sm: { span: 15 } }"
                                        prop="description"
                                    >
                                        <BaseTextarea
                                            v-model="form.description"
                                            :max-length="10000"
                                            placeholder="请输入新技术描述"
                                        />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </a-col>
                    </a-form-model>
                </a-row>
            </a-form>
        </a-modal>

        <a-modal
            title="新技术类型"
            :visible="treeVisible"
            :confirm-loading="confirmLoading"
            class="normal-modal"
            ok-text="提交"
            @ok="editTreeOk"
            @cancel="editTreeCancel"
        >
            <div class="about-master-container">
                <a-form-model ref="treeForm" :model="treeFrom" :rules="treeRules">
                    <a-col>
                        <a-row>
                            <a-col span="12">
                                <a-form-model-item prop="name" label="类型名称">
                                    <BaseInput v-model="treeFrom.name" />
                                </a-form-model-item>
                            </a-col>
                            <a-col span="12">
                                <a-form-model-item label="父节点">
                                    <BaseInput v-model="treeFrom.parentName" disabled :maxLength="20" />
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                    </a-col>
                </a-form-model>
            </div>
        </a-modal>
    </base-breadcrumb>
</template>

<script>
import { STable } from '@/components'
import {mapGetters } from 'vuex'
import {
    getTechnologyTemplate,
    addTechnologyTemplate,
    editTechnologyTemplate,
    getStatus,
    treeList,
    treeAdd,
    treeUpdate,
    treeIsDelete,
    treeDelete,
    templateDelete,
    downExcel
} from '@/api/technology'
import ServiceExportMould from '@/components/ServiceExportMould'
import ARow from 'ant-design-vue/es/grid/Row'
import { technologyApiUrl } from '@/api/config.js'
const columns = [
    {
        title: '序号',
        width: '65px',

        dataIndex: 'number'
    },
    {
        title: '新技术名称',
        width: 200,
        dataIndex: 'technicalName'
    },
    {
        title: '实物量单位',
        width: 180,
        dataIndex: 'entityMeasureUnit'
    },
    {
        title: '新技术描述',
        dataIndex: 'description',
    },
    {
        title: '状态',
        width: 100,
        dataIndex: 'status',
        scopedSlots: { customRender: 'status' }
    },
    {
        title: '操作',
        dataIndex: 'action',
        width: '150px',
        scopedSlots: { customRender: 'action' }
    }
]

const statusMap = {
    0: {
        status: 'default',
        text: '已停用'
    },
    1: {
        status: 'processing',
        text: '已启用'
    }
}
export default {
    name: 'a' + Date.now(),
    components: {
        ARow,
        STable,
        ServiceExportMould
    },
    computed: {
        ...mapGetters(['GET_REDRESS_PERCENTAGE']),
        canAdd() {
            if (this.selectTree) {
                if (this.selectTree.dataRef.children.length === 0) {
                    return false
                }
            }
            return true
        }
    },
    data() {
        const  validateNumber = (rule,value) => {
            const reg = /^(([1-9]{1}\d*)|(0{1}))((\.\d{1,10})?)$/
            if(!value) {
                return Promise.reject('请输入序号');
            }
            if(!reg.test(value)) {
                return Promise.reject('请输入正确的序号');
            }
            return Promise.resolve()
        }
        this.columns = columns
        return {
            titleName: undefined,
            title: undefined,
            visible: false, //新增上报模块展示隐藏
            treeVisible: false,
            confirmLoading: false,
            getTreeLoading: false,
            mdl: null,
            technologyApiUrl: technologyApiUrl,
            queryParam: {},
            // 加载数据方法 必须为 Promise 对象
            loadData: (parameter) => {
                const requestParameters = Object.assign({}, parameter, this.queryParam)
                if (this.selectTree) {
                    requestParameters.treeId = this.selectTree.id
                }
                return getTechnologyTemplate(null, requestParameters).then((res) => {
                    return res
                })
            },
            searchArr: [
                { name: '新技术名称', value: 'templateName', type: 'input' },
                {
                    name: '状态',
                    value: 'status',
                    type: 'select',
                    data: [
                        { value: 1, label: '启用' },
                        { value: 0, label: '停用' }
                    ]
                },
                { name: '新技术描述', value: 'description', type: 'input' }
                // {
                //   name: '排序', value: 'sort', type: 'select',
                //   data: [
                //     { value: 1, label: '正序' },
                //     { value: 2, label: '倒序' }
                //   ]
                // }
            ],
            posttype: 0,
            form: {},
            rules: {
                technicalName: [{ required: true, whitespace: true, message: '请输入新技术名称', trigger: 'change' }],
                entityMeasureUnit: [
                    { required: true, whitespace: true, message: '请输入实物量单位', trigger: 'change' }
                ],
                number: [{ required: true,validator:validateNumber, trigger: 'blur' }],
                description: [{ required: true, whitespace: true, message: '请输入新技术描述', trigger: 'change' }]
            },

            treeFrom: {},
            treeRules: {
                name: [{ required: true, whitespace: true, message: '请输入类型名称"', trigger: 'change' }]
            },
            treeData: [],
            selectedKeys: [],
            replaceFields: {
                children: 'children',
                title: 'name',
                key: 'id'
            },

            expandedKeys: [],
            expandedKeysTemp: [],
            searchValue: '',
            autoExpandParent: true,
            dataList: [],
            editAble: false,
            selectTree: null,
            loadingExcel: false
        }
    },
    filters: {
        statusFilter(type) {
            return statusMap[type].text
        },
        statusTypeFilter(type) {
            return statusMap[type].status
        }
    },
    mounted() {
        this.getTree()
    },
    methods: {
        downExcel() {
            this.loadingExcel = true
            console.log(this.selectTree)
            downExcel({ treeId: this.selectTree.id },this.selectTree.name+'.xls')
                .then((res) => {
                    this.loadingExcel = false
                })
                .catch(() => {
                    this.loadingExcel = false
                })
        },
        search(val) {
            this.queryParam = val || {}
            this.$refs.table.refresh(true)
        },
        async delTree() {
            this.confirmLoading = true
            let res = await treeIsDelete({ id: this.selectTree.id })
            this.confirmLoading = false
            if (res.code === this.SUCCESS_CODE) {
                if (res.data) {
                    await this.$delList3(
                        treeDelete,
                        () => {
                            this.selectTree = null
                            this.$refs.table.refresh(true)
                            this.getTree()
                        },
                        { id: this.selectTree.id }
                    )
                } else {
                    this.$noticeWarning('子级有新技术的不能进行删除')
                }
            }
        },
        editTreeOk() {
            this.$refs.treeForm.validate(async (valid) => {
                if (valid) {
                    this.confirmLoading = true
                    let res
                    // this.treeFrom.parentId = Number(this.treeFrom.parentId)
                    if (this.treeFrom.id) {
                        res = await treeUpdate(this.treeFrom)
                    } else {
                        res = await treeAdd(this.treeFrom)
                    }
                    this.confirmLoading = false
                    if (res.code === this.SUCCESS_CODE) {
                        this.getTree(this.selectedKeys[0])
                        this.editTreeCancel()
                    }
                } else {
                    this.$noticeWarning('请填写完整')
                }
            })
        },
        editTreeCancel() {
            this.$refs.treeForm.clearValidate()
            // this.selectTree = { name: '', parentName: '' }
            this.treeVisible = false
        },
        addTree(type) {
            if (this.selectTree) {
                if (type === 1) {
                    console.log(this.selectTree)
                    this.treeFrom = {}
                    this.treeFrom.parentName = this.selectTree.name
                    this.treeFrom.parentId = this.selectTree.id
                } else {
                    this.treeFrom = this.$clone(this.selectTree)
                }
                this.treeVisible = true
            } else {
                this.$noticeWarning('请选择父级新技术类型')
            }
        },
        onChange(e) {
            const value = e.target.value
            if (!value) {
                this.autoExpandParent = true
                this.expandedKeys = this.$clone(this.expandedKeysTemp)
                this.searchValue = ''
            } else {
                const expandedKeys = this.dataList
                    .map((item) => {
                        if (item.title.indexOf(value) > -1) {
                            return this.getParentKey(item.key, this.treeData)
                        }
                        return null
                    })
                    .filter((item, i, self) => item && self.indexOf(item) === i)
                Object.assign(this, {
                    expandedKeys,
                    searchValue: value,
                    autoExpandParent: true
                })
            }
        },
        generateList(data) {
            for (let i = 0; i < data.length; i++) {
                const node = data[i]
                const key = node.key
                const title = node.title
                // this.dataList.push({ key, title: key })
                this.dataList.push({ key, title })
                if (node.children) {
                    this.generateList(node.children)
                }
            }
        },
        getParentKey(key, tree) {
            let parentKey
            for (let i = 0; i < tree.length; i++) {
                const node = tree[i]
                if (node.children) {
                    if (node.children.some((item) => item.key === key)) {
                        parentKey = node.key
                    } else if (this.getParentKey(key, node.children)) {
                        parentKey = this.getParentKey(key, node.children)
                    }
                }
            }
            return parentKey
        },
        async getTree(expandedId) {
            return new Promise(async (resolve) => {
                this.getTreeLoading = true
                let res = await treeList()
                this.getTreeLoading = false
                if (res.code === this.SUCCESS_CODE) {
                    this.treeData = this.replaceList(res.data)
                    this.selectedKeys = this.selectedKeys.length ? this.selectedKeys : [this.treeData[0].id]
                    this.expandedKeys = this.expandedKeys.length ? this.expandedKeys : [this.treeData[0].id]
                    if (expandedId) {
                        this.expandedKeys.push(expandedId)
                    }
                    if (!this.selectTree) {
                        this.selectTree = { ...this.treeData[0], dataRef: { children: [1] } }
                        this.editAble = false
                    }
                    this.generateList(this.treeData)
                }
                resolve()
            })
        },
        replaceList(list) {
            return list.map((v) => {
                v.scopedSlots = { title: 'title' }
                v.key = v[this.replaceFields.key]
                v.title = v[this.replaceFields.title]
                if (v.children && v.children.length) {
                    v.children = this.replaceList(v.children)
                }
                return v
            })
        },
        getParentNode(list, parentId) {
            list.map((v) => {
                if (v.id == parentId) {
                    this.selectTree.parentName = v.name
                } else {
                    v.children && v.children.length && this.getParentNode(v.children, parentId)
                }
            })
        },
        onSelect(selectedKeys, info) {
            console.log(info)
            this.selectedKeys = selectedKeys
            if (selectedKeys.length) {
                this.selectTree = info.selectedNodes[0].data.props
                this.editAble = this.selectTree.id !== '0'
                this.selectTree.parentId !== 0 && this.getParentNode(this.treeData, this.selectTree.parentId)
            } else {
                this.selectTree = null
                this.editAble = false
            }
            this.$refs.table.refresh(true)
        },
        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys
            this.expandedKeysTemp = expandedKeys
            this.autoExpandParent = false
        },
        handleAdd() {
            this.form = {}
            this.visible = true
            this.posttype = 0
            this.title = '新技术'
        },
        handleEdit(record) {
            this.visible = true
            this.posttype = 1
            this.form = { ...record }
            this.title = '新技术'
        },
        handleOk() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.confirmLoading = true
                    switch (this.posttype) {
                        case 0:
                            this.form.treeId = this.selectTree.id
                            addTechnologyTemplate(this.form)
                                .then((res) => {
                                    this.confirmLoading = false
                                    if (res.code == 200) {
                                        this.$message.success('新增成功')
                                        this.visible = false
                                        this.$refs.table.refresh()
                                    }
                                })
                                .catch((res) => {
                                    this.confirmLoading = false
                                })
                            break
                        case 1:
                            editTechnologyTemplate(this.form)
                                .then((res) => {
                                    this.confirmLoading = false
                                    if (res.code == 200) {
                                        this.$message.success('修改成功')
                                        this.visible = false
                                        this.$refs.table.loadData()
                                    }
                                })
                                .catch((res) => {
                                    this.confirmLoading = false
                                })
                    }
                }
            })
        },
        handleCancel() {
            this.visible = false
            this.form = {}
            this.$refs.form.clearValidate()
        },
        handleSwitch(record, e) {
            let that = this
            that.$confirm({
                title: '确定' + ['停用', '启用'][e] + '？',
                onOk() {
                    return getStatus(record).then((res) => {
                        if (res.code == 200) {
                            that.$message.success(['停用', '启用'][e] + '成功')
                            that.$refs.table.loadData()
                        }
                    })
                }
            })
        },
        handleDel(record) {
            this.$delList3(
                templateDelete,
                () => {
                    this.search()
                },
                { id: record.technicalId }
            )
        }
    }
}
</script>
